package com.example.test;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class ABCPrinter {
    private static final ReentrantLock lock = new ReentrantLock();
    private static final Condition condA = lock.newCondition();
    private static final Condition condB = lock.newCondition();
    private static final Condition condC = lock.newCondition();
    private static int state = 0;

    public static void print(String name, int target, Condition self, Condition next) {
        for (int i = 0; i < 10; i++) {
            lock.lock();
            try {
                while (state % 3 != target) {
                    self.await();
                }
                System.out.println(name);
                state++;
                next.signal();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) {
        new Thread(() -> print("A", 0, condA, condB)).start();
        new Thread(() -> print("B", 1, condB, condC)).start();
        new Thread(() -> print("C", 2, condC, condA)).start();
    }
}
